package com.baizhi.controller;

import com.baizhi.feignclient.ProductClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private DiscoveryClient discoveryClient;    // 服务发现客户端

    @Autowired
    private LoadBalancerClient loadBalancerClient;  // 负载均衡客户端组件

    @Autowired
    private RestTemplate restTemplate;  // 具有负载均衡的RestTemplate对象

    @Autowired
    private ProductClient productClient;    // OpenFeign客户端

    @GetMapping("/invoke")
    public String invokeProduct() {
        log.info("调用用户服务 ...");

        // 一、使用RestTemplate调用商品服务
//        String result = new RestTemplate().getForObject("http://localhost:9090/product?id=21", String.class);

        // 二、使用Ribbon组件实现负载均衡
        // 1.DiscoveryClient
//        List<ServiceInstance> serviceInstances = discoveryClient.getInstances("PRODUCTS");
//        for (ServiceInstance serviceInstance : serviceInstances) {
//            log.info("服务主机：{}, 服务端口：{}, 服务uri：{}", serviceInstance.getHost(), serviceInstance.getPort(), serviceInstance.getUri());
//        }
//        String result = new RestTemplate().getForObject(serviceInstances.get(0).getUri()+"/product?id=21", String.class);

        // 2.LoadBalancerClient
        // 已经进行负载均衡之后返回节点，轮询策略
//        ServiceInstance serviceInstance = loadBalancerClient.choose("PRODUCTS");
//        String result = new RestTemplate().getForObject(serviceInstance.getUri()+"/product?id=21", String.class);

        // 3.@LoadBalanced注解
//        String result = this.restTemplate.getForObject("http://PRODUCTS/product?id=21", String.class);

        // 三、OpenFeign方式
        String result = productClient.product(21);

        log.info("商品服务调用结果：{}", result);
        return result;
    }
}
